package controllers;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;

import models.GameManager;
import play.data.DynamicForm;
import play.data.Form;
import play.libs.Json;
import play.mvc.*;
import views.html.*;

/**
 * Front controller of application.
 */
public class Application extends Controller
{

    /**
     * Index action.
     * 
     * @return Result object.
     */
    public static Result index()
    {
        try
        {
            boolean isGameInProgress = GameManager.roomCreated();
            if (!isGameInProgress)
            {
                flash("info",
                        "Choose your opponents and settings to create new game room.");
            }
            else
            {
                flash("info", "Choose your nickname and join existing game.");
            }
            return ok(inform.render(isGameInProgress));
        }
        catch (Exception e)
        {
            flash("error",
                    "Can't get game status information: " + e.getMessage());
            return ok(inform.render(false));
        }
    }

    public static Result gameRoom()
    {
        DynamicForm requestData = Form.form().bindFromRequest();
        String username = requestData.get("username");
        String uuid = "bla";
        String type2 = requestData.get("type2");
        String type3 = requestData.get("type3");
        String type4 = requestData.get("type4");
        String initCash = requestData.get("in_cash");
        String initFee = requestData.get("in_fee");

        try
        {
            int initCashInt = 500;
            int initFeeInt = 75;
            if ((username == null) || username.trim().equals(""))
            {
                throw new Exception("Please choose a valid username.");
            }
            if (username.length() > 12)
            {
                throw new Exception("Maximum username length is 12.");
            }
            if ((initCash != null) && (initFee != null))
            {
                initCashInt = Integer.parseInt(initCash);
                initFeeInt = Integer.parseInt(initFee);
                if ((initCashInt < 500) || (initCashInt > 1000000))
                {
                    throw new Exception(
                            "Start cash must fit into [500; 1 000 000].");
                }
                if ((initFeeInt < 0) || (initFeeInt > 20000))
                {
                    throw new Exception(
                            "Enter fee must fit into [500; 20 000].");
                }
            }
            uuid = GameManager.futureJoin(username, type2, type3, type4,
                    initCashInt, initFeeInt);
        }
        catch (Exception e)
        {
            flash("error", e.getMessage());
            return redirect(routes.Application.index());
        }

        return ok(table.render(username, uuid));
    }

    public static WebSocket<JsonNode> playing(final String uuid)
    {
        return new WebSocket<JsonNode>()
        {
            @Override
            public void onReady(final WebSocket.In<JsonNode> in,
                    final WebSocket.Out<JsonNode> out)
            {
                try
                {
                    GameManager.gameJoin(uuid, in, out);
                }
                catch (Exception e)
                {
                    ObjectNode event = Json.newObject();
                    event.put("type", "consoleMsg");
                    event.put("msgType", "danger");
                    event.put("msg", e.getMessage());
                    out.write(event);
                    out.close();
                }
            }
        };
    }

}
